package com.example.myapplication;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapplication.AsyncTasks.GetJsonCallBack;
import com.example.myapplication.AsyncTasks.GetJsonTask;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import java.util.ArrayList;

public class NoteViewFragment extends Fragment  {



  enum NoteOperation
  {
    OPEN_CURRENT_NOTE,
    CREATE_EMPTY_NOTE
  }

  LinearLayout nullTipLayout;
  LinearLayout multiSelectionButtomLayout;
  LinearLayout multiSelectionTopLayout;

  RelativeLayout classifyLayout;
  RefreshLayout refreshLayout;
  ImageView arrowImage;
  ImageButton imageButton;
  ImageButton remoteButton;
  ImageButton settingButton;

  ImageButton deleteButton;
  ImageButton allSelectionButton;
  ImageButton closeMultiSelectionButton;

  Toolbar toolbar;
  View mainView;
  View maskView;

  TextView noteNumberText;
  TextView selectionNumberText;
  TextView classifyTitleText;
  RecyclerView noteListView;

  SearchView searchView;



  String userAccount;
  String userName;
  boolean isMultiSelectMode = false;
  boolean isOnDeletePage = false;
  NoteArrayListAdapter noteArrayListAdapter;
  NoteDataBaseHelper noteDataBaseHelper;

  ArrayList<Note> noteArrayList;
  ArrayList<Note> selectedItems;
  ArrayList<Note> favourList;

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
      userAccount = getArguments().getString("userAccount");
      userName = getArguments().getString("userName");
      noteDataBaseHelper = new NoteDataBaseHelper(this.getContext(), this);


    }
  }

  @Nullable @Override
  public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    mainView = inflater.inflate(R.layout.notes_fragment_layout, container, false);
    return mainView;
  }

  @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Init();
    InitDropDownMenu();
    InitRefreshLayout();
    InitSettingButton();
    InitRemoteButton();
    InitCreateButton();
    InitDeleteButton();
    InitSearchView();
    InitAllSelectedButton();
    GetData();
    ShowData();

  }

  private void InitSearchView() {

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
      @Override public boolean onQueryTextSubmit(String query) {
        if (query.isEmpty()) {
          noteArrayListAdapter.UpdateList(noteArrayList);

        }
        return true;
      }

      @Override public boolean onQueryTextChange(String newText) {
        if (newText.isEmpty()) {

          noteArrayListAdapter.UpdateList(noteArrayList);
        }

        DataFilter(newText);
        return true;
      }
    });
  }

  private void DataFilter(String string) {
    ArrayList<Note> arrayList;
    arrayList = SelectData(string);

    noteArrayListAdapter.UpdateList(arrayList);
    UpdateNoteNumberText(arrayList.size());

  }

  private ArrayList<Note> SelectData(String query) {

    ArrayList<Note> data = new ArrayList<>();
    for (Note dictionaryInfo : noteArrayList) {
      if (dictionaryInfo.getNoteTitle().toLowerCase().contains(query.toLowerCase())) {

        data.add(dictionaryInfo);
      }
    }

    return data;

  }

  private void InitRemoteButton() {
    remoteButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        ShowRemotePanel(v);
      }
    });
  }

  private void ShowRemotePanel(View v) {
    PopupMenu popupMenu = new PopupMenu(mainView.getContext(), v);
    MenuInflater inflater = popupMenu.getMenuInflater();
    inflater.inflate(R.menu.remote_menu, popupMenu.getMenu());
    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
      @Override public boolean onMenuItemClick(MenuItem item) {
        if (item.getItemId() == R.id.upload_data) {
          noteDataBaseHelper.UpLoadDataToRemote(refreshLayout);
          Toast.makeText(mainView.getContext(), "成功上传数据", Toast.LENGTH_SHORT).show();
        } else {

          noteDataBaseHelper.DownLoadDataFromRemote(refreshLayout, NoteViewFragment.this);



          Toast.makeText(mainView.getContext(), "成功同步远端数据", Toast.LENGTH_SHORT).show();

        }
        return true;
      }
    });
    popupMenu.show();
  }

  private void InitRefreshLayout() {
    refreshLayout.setOnRefreshListener(new OnRefreshListener() {
      @Override public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishRefresh(1000);
        UpdateNoteData();
      }
    });
    //refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
    //  @Override public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
    //
    //  }
    //});
    refreshLayout.setEnableLoadMore(false);
  }

  private void InitAllSelectedButton() {
    allSelectionButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        noteArrayListAdapter.SelectOrDeselectAll();
      }
    });
  }

  private void InitDeleteButton() {
    deleteButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        selectedItems = noteArrayListAdapter.GetMultiSelectedItem();
        if (selectedItems.size() == 0) {
          return;
        }
        Dialog dialog = new Dialog(getContext());
        dialog.setContentView(R.layout.dialog_delete_window);
        Button positiveButton = dialog.findViewById(R.id.positive_button);
        positiveButton.setOnClickListener(new View.OnClickListener() {
          @Override public void onClick(View v) {
            //删除操作
            DeleteSelectedItems();
            dialog.dismiss();
          }
        });
        Button negativeButton = dialog.findViewById(R.id.negative_button);
        negativeButton.setOnClickListener(new View.OnClickListener() {
          @Override public void onClick(View v) {
            dialog.dismiss();
          }
        });
        Window window = dialog.getWindow();
        if (window != null) {
          window.setGravity(Gravity.BOTTOM);

        }
        dialog.show();
      }
    });

  }

  private void DeleteSelectedItems() {
    if (selectedItems == null || selectedItems.size() == 0) {
      return;
    }
    //先对本地进行删除
    for (Note note : selectedItems) {
      noteArrayList.remove(note);
    }
    noteArrayListAdapter.UpdateList(noteArrayList);
    int flag = noteDataBaseHelper.DeleteMultiNoteByID(selectedItems);
    if (flag == 1) {
      Toast.makeText(mainView.getContext(), "删除了" + selectedItems.size() + "个数据",
          Toast.LENGTH_SHORT).show();
    } else {
      Toast.makeText(mainView.getContext(), "删除失败", Toast.LENGTH_SHORT).show();
    }
    CloseMultiSelectPanel();
    ClearMultiSelectData();
    isMultiSelectMode=false;
    noteArrayListAdapter.SetMultiSelectMode(false);
    UpdateNoteNumberText(noteArrayList.size());

  }

  private void InitCreateButton() {
    imageButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {

        JumpToNote(NoteOperation.CREATE_EMPTY_NOTE, null);
      }
    });
  }

  public void JumpToNote(NoteOperation operation,Note note) {

    if (operation == NoteOperation.CREATE_EMPTY_NOTE) {
      note = new Note(userName, userAccount, null);
    }


    Intent intent = new Intent(mainView.getContext(), NoteContentActivity.class);
    Bundle bundle = new Bundle();
    bundle.putSerializable("currentNote",note);
    bundle.putString("userAccount", userAccount);
    bundle.putString("userName", userName);
    intent.putExtras(bundle);
    startActivity(intent);

  }

  private void InitSettingButton() {
    settingButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        ShowSettingPanel(v);
      }
    });
    closeMultiSelectionButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        CloseMultiSelectPanel();
        ClearMultiSelectData();
        isMultiSelectMode=false;
        noteArrayListAdapter.SetMultiSelectMode(false);
        //noteArrayListAdapter.SelectOrDeselectAll();

      }
    });
  }

  private void ClearMultiSelectData() {
    selectedItems.clear();
  }

  private void ShowSettingPanel(View v) {
    PopupMenu popupMenu = new PopupMenu(mainView.getContext(), v);
    MenuInflater inflater = popupMenu.getMenuInflater();
    inflater.inflate(R.menu.menu_item, popupMenu.getMenu());
    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
      @Override public boolean onMenuItemClick(MenuItem item) {
        if (item.getItemId() == R.id.delete_data) {
          isMultiSelectMode = true;
          noteArrayListAdapter.SetMultiSelectMode(isMultiSelectMode);
        }
        ShowMultiSelectPanel();
        return true;
      }
    });
    popupMenu.show();

  }

  private void ShowMultiSelectPanel() {
    multiSelectionTopLayout.setVisibility(View.VISIBLE);
    multiSelectionButtomLayout.setVisibility(View.VISIBLE);
    UpdateSelection(selectedItems.size());

  }

  public void UpdateSelection(int number) {
    selectionNumberText.setText(getString(R.string.selection_number, String.valueOf(number)));

  }



  private void CloseMultiSelectPanel() {
    multiSelectionTopLayout.setVisibility(View.INVISIBLE);
    multiSelectionButtomLayout.setVisibility(View.INVISIBLE);
    noteArrayListAdapter.SetMultiSelectMode(false);

  }

  private void Init() {
    selectedItems = new ArrayList<>();
    searchView = mainView.findViewById(R.id.search_view);
    toolbar = mainView.findViewById(R.id.toolbar);
    classifyLayout = mainView.findViewById(R.id.classify_layout);
    maskView = mainView.findViewById(R.id.mask_view);
    arrowImage = mainView.findViewById(R.id.classify_arrow);
    settingButton = mainView.findViewById(R.id.setting_button);
    imageButton = mainView.findViewById(R.id.create_button);
    nullTipLayout = mainView.findViewById(R.id.null_note_tip);
    noteListView = mainView.findViewById(R.id.info_list);
    noteNumberText = mainView.findViewById(R.id.note_number_tip);
    multiSelectionButtomLayout = mainView.findViewById(R.id.multi_selection_buttom_layout);
    deleteButton = mainView.findViewById(R.id.delete_button);
    allSelectionButton = mainView.findViewById(R.id.all_select_button);
    selectionNumberText = mainView.findViewById(R.id.selection_number_text);
    closeMultiSelectionButton = mainView.findViewById(R.id.close_multi_selection_button);
    multiSelectionTopLayout = mainView.findViewById(R.id.multi_selection_top_layout);
    refreshLayout = mainView.findViewById(R.id.refreshLayout);
    remoteButton = mainView.findViewById(R.id.remote_button);
    classifyTitleText = mainView.findViewById(R.id.classify_title);
  }

  private void InitDropDownMenu() {

    classifyLayout.setOnTouchListener(new View.OnTouchListener() {
      @Override public boolean onTouch(View v, MotionEvent event) {
        //设置条件判断类型
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
          ShowClassifyMenu();
        }

        return true;
      }
    });
  }

  private void ShowData() {
    int number=noteArrayList.size();
    noteNumberText.setText(getString(R.string.note_number, String.valueOf(number)));



    noteArrayListAdapter = new NoteArrayListAdapter(noteArrayList,this);
    noteListView.setAdapter(noteArrayListAdapter);
    noteListView.setLayoutManager(new LinearLayoutManager(this.getContext()));
    if (number == 0) {
      ShowNullTipLayout();
      return;
    }
    HideNullTipLayout();
    //ItemTouchHelper.Callback callback = new SwipeItemTouchHelperCallBack(noteArrayListAdapter);
    //ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
    //itemTouchHelper.attachToRecyclerView(noteListView);
  }

  private void HideNullTipLayout() {
    nullTipLayout.setVisibility(View.INVISIBLE);
  }

  private void ShowNullTipLayout() {
    nullTipLayout.setVisibility(View.VISIBLE);
  }

  public void UpdateNoteData() {
    noteArrayList = noteDataBaseHelper.GetNoteListByAccount(userAccount);
    favourList = noteDataBaseHelper.GetFavourNoteByAccount(userAccount);
    int number=noteArrayList.size();
    UpdateNoteNumberText(number);
    noteArrayListAdapter.UpdateList(noteArrayList);

    if (number == 0) {
      nullTipLayout.setVisibility(View.VISIBLE);
      return;
    }

    nullTipLayout.setVisibility(View.INVISIBLE);


  }
  public void UpdateNoteNumberText(int number) {
    noteNumberText.setText(getString(R.string.note_number, String.valueOf(number)));
    if (number == 0) {
      ShowNullTipLayout();
    } else {
      HideNullTipLayout();

    }
  }

  private void GetData() {
    noteDataBaseHelper.Open();

    noteArrayList = noteDataBaseHelper.GetNoteListByAccount(userAccount);
    favourList = noteDataBaseHelper.GetFavourNoteByAccount(userAccount);
    noteDataBaseHelper.Close();
  }

  void ShowClassifyMenu() {


    //显示遮罩层
    maskView.setVisibility(View.VISIBLE);
    Animation animation1 =
        AnimationUtils.loadAnimation(mainView.getContext(), R.anim.arrow_flip_up);
    animation1.setFillAfter(true);

    arrowImage.startAnimation(animation1);


    View dropDownView = getLayoutInflater().inflate(R.layout.dropdown_menu, null);
    LinearLayout allTypeLayout = dropDownView.findViewById(R.id.all_type_layout);

    TextView allTypeNumber = dropDownView.findViewById(R.id.all_type_number);
    allTypeNumber.setText(String.valueOf(noteArrayList.size()));

    LinearLayout favourTypeLayout = dropDownView.findViewById(R.id.favour_type_layout);
    TextView favourTypeNumber = dropDownView.findViewById(R.id.favour_type_number);
    favourTypeNumber.setText(String.valueOf(favourList.size()));

    //创建PopupWindow对象
    PopupWindow popupWindow = new PopupWindow(dropDownView, ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT);
    popupWindow.setFocusable(true);// 设置焦点，使下拉菜单可以响应点击事件
    popupWindow.setTouchable(true);
    popupWindow.setOutsideTouchable(true);

    popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));// 设置背景，可以自定义
    //显示下拉菜单

    popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
      @Override public void onDismiss() {
        maskView.setVisibility(View.GONE);
        Animation animation2 =
            AnimationUtils.loadAnimation(mainView.getContext(), R.anim.arrow_flip_down);
        arrowImage.startAnimation(animation2);
        animation2.setFillAfter(true);

      }
    });

    allTypeLayout.setOnTouchListener(new View.OnTouchListener() {
      @Override public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
          AllTypeDataFilter();
          popupWindow.dismiss();
        }

        return true;
      }
    });
    favourTypeLayout.setOnTouchListener(new View.OnTouchListener() {
      @Override public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
          FavourDataFilter();
          popupWindow.dismiss();
        }
        return true;
      }
    });

    popupWindow.showAsDropDown(toolbar);// 在指定的锚点视图下方显示菜单
  }

  private void AllTypeDataFilter() {
    if (noteArrayList.size() == 0) {
      return;
    }
    classifyTitleText.setText("全部");
    noteArrayListAdapter.UpdateList(noteArrayList);
  }

  private void FavourDataFilter() {
    if (favourList.size() == 0) {
      return;
    }
    classifyTitleText.setText("收藏");
    noteArrayListAdapter.UpdateList(favourList);

  }

  @Override public void onResume() {
    super.onResume();
    noteDataBaseHelper.Open();

    if(noteArrayListAdapter!=null)
      UpdateNoteData();
  }



}
